package gen

import (
	"errors"

	"gitee.com/zawei/yggdrasil/internal/yggdrasil/gen/generator"
	"gitee.com/zawei/yggdrasil/pkg/config"
	"gitee.com/zawei/yggdrasil/third_party/urfave/cli"
)

var serviceCmd = &cli.Command{
	Name:    "service",
	Aliases: []string{"s"},
	Usage:   "Initiate a service",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:    "gen_transport",
			Aliases: []string{"g_t"},
			Value:   "grpc",
		},
	},
	Action: func(ctx *cli.Context) error {
		return genService(ctx.Args().Slice())
	},
}

func init() {
	genCmd.Subcommands = append(genCmd.Subcommands, serviceCmd)
}

func genService(args []string) error {
	if len(args) == 0 {
		return errors.New("you must provide a name for the service")
	}
	if config.Get("gen.transport").String() == "grpc" {
		if !checkProtoc() {
			return nil
		}
	}
	g := generator.NewGenerateService(
		args[0],
		config.Get("gen.transport").String(),
		config.Get("methods").StringSlice(),
	)
	if err := g.Generate(); err != nil {
		return err
	}
	return nil
}
